package com.baijiayun.live.ui.toolbox.custom_webpage;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.ProgressBar;

import androidx.appcompat.app.AlertDialog;

import com.baijiayun.live.ui.BuildConfig;
import com.baijiayun.live.ui.R;
import com.baijiayun.live.ui.base.BaseDialogFragment;
import com.baijiayun.liveuibase.utils.ThemeDataUtil;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.export.external.interfaces.WebResourceError;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

/**
 * Created by yongjiaming on 2020/7/13
 * Describe:
 */
public class BaseWebViewDialogFragment extends BaseDialogFragment {

    private boolean isDestroyed = false;
    private static final String windowName = "bjlapp";
    protected WebView mWebView;

    @Override
    protected int getLayoutId() {
        return R.layout.bjy_fragment_quiz;
    }

    @Override
    protected void init(Bundle savedInstanceState, Bundle arguments) {
        if(getArguments() != null){
            initWebClient();
            loadUrl(getArguments().getString("url"));
        }
        setCancelable(false);
    }

    public void setCloseBtnStatus(boolean show) {
        if (show) {
            if (isQueryPlusNull()) return;
            editable(true);
            editText(getString(R.string.live_quiz_close));
            editClick(v -> showCloseDlg());
        } else {
            editable(false);
        }
    }


    private void showCloseDlg() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        AlertDialog dialog = builder.setMessage(R.string.live_quiz_dialog_tip)
                .setPositiveButton(R.string.live_quiz_dialog_confirm, (dialog12, which) -> {
                    dialog12.dismiss();
                    closeDialogFragment();
                }).setNegativeButton(R.string.live_quiz_dialog_cancel, (dialog1, which) -> dialog1.dismiss()).create();
        dialog.show();
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(
                ThemeDataUtil.getColorFromThemeConfigByAttrId(getContext(), R.attr.base_theme_live_product_color));
        dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(
                ThemeDataUtil.getColorFromThemeConfigByAttrId(getContext(), R.attr.base_theme_live_product_color));
    }

    @SuppressLint("SetJavaScriptEnabled")
    private void initWebClient() {
        mWebView = ((WebView) $.id(R.id.wv_quiz_main).view());
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.addJavascriptInterface(this, windowName);
        mWebView.setVerticalScrollBarEnabled(false);

        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.getSettings().setAppCacheMaxSize(1024 * 1024 * 8);
        String appCachePath = getActivity().getApplicationContext().getCacheDir().getAbsolutePath();
        mWebView.getSettings().setAppCachePath(appCachePath);
        mWebView.getSettings().setAppCacheEnabled(true);
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);

        //chrome client
        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                ((ProgressBar) $.id(R.id.pb_web_view_quiz).view()).setProgress(newProgress);
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public void onReceivedTitle(WebView webView, String s) {
                super.onReceivedTitle(webView, s);
                title(s);
            }
        });

        //webView client
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                $.id(R.id.pb_web_view_quiz).visible();
                setCloseBtnStatus(true);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if(isDestroyed) return;
                $.id(R.id.pb_web_view_quiz).gone();
            }

            @Override
            public void onReceivedSslError(WebView webView, SslErrorHandler sslErrorHandler, com.tencent.smtt.export.external.interfaces.SslError sslError) {
                sslErrorHandler.proceed();
            }

            @TargetApi(Build.VERSION_CODES.M)
            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
                // code -11 net::ERR_BAD_SSL_CLIENT_AUTH_CERT 忽略https证书问题
                if(error.getErrorCode() != -11) {
                    $.id(R.id.pb_web_view_quiz).gone();
                }
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                if(errorCode != -11){
                    $.id(R.id.pb_web_view_quiz).gone();
                }
            }
        });
    }

    public void loadUrl(String url) {
        if(!TextUtils.isEmpty(url)){
            ((WebView) $.id(R.id.wv_quiz_main).view()).loadUrl(url);
        }
    }

    @Override
    public void onDestroy() {
        mWebView.destroy();
        super.onDestroy();
        isDestroyed = true;
    }

    protected void closeDialogFragment(){
        // do nothing
    }
}
